package com.trial.eyefollowupapp.screens

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.unit.*
import androidx.navigation.NavHostController
import coil.compose.rememberAsyncImagePainter
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import com.trial.eyefollowupapp.RetrofitClient
import com.trial.eyefollowupapp.RecordDetailResponse
import com.trial.eyefollowupapp.Diagnosis
import com.trial.eyefollowupapp.theme.AppAnimations
import com.trial.eyefollowupapp.theme.AppDimens
import androidx.compose.foundation.background
import androidx.compose.animation.core.tween
// 在文件顶部添加导入
import com.trial.eyefollowupapp.BuildConfig

// 添加缺失的导入
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.ui.graphics.Color

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun RecordDetailScreen(navController: NavHostController, recordId: Int) {
    var record by remember { mutableStateOf<RecordDetailResponse?>(null) }
    var loading by remember { mutableStateOf(true) }
    var errorMsg by remember { mutableStateOf("") }
    var showContent by remember { mutableStateOf(false) }

    LaunchedEffect(Unit) {
        try {
            val response = withContext(Dispatchers.IO) {
                RetrofitClient.instance.getRecordDetail(recordId)
            }

            if (response.isSuccessful) {
                record = response.body()
            } else {
                errorMsg = "获取记录详情失败"
            }
        } catch (e: Exception) {
            errorMsg = "网络请求失败: ${e.message}"
        } finally {
            loading = false
            showContent = true
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("报告详情") },
                navigationIcon = {
                    IconButton(onClick = { navController.popBackStack() }) {
                        Icon(Icons.Filled.ArrowBack, contentDescription = "返回")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            )
        },
        contentWindowInsets = WindowInsets(0, 0, 0, 0)
    ) {
        if (loading) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator(
                    color = MaterialTheme.colorScheme.primary
                )
            }
        } else if (errorMsg.isNotEmpty()) {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Text(
                    errorMsg,
                    color = MaterialTheme.colorScheme.error,
                    style = MaterialTheme.typography.bodyLarge
                )
            }
        } else if (record != null) {
            AnimatedVisibility(
                visible = showContent,
                enter = fadeIn(animationSpec = tween(durationMillis = AppAnimations.durationMedium))
            ) {
                LazyColumn(
                    // 1. 恢复 fillMaxSize，让它占满整个内容区域
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(it)          // Scaffold 的 innerPadding
                        .padding(horizontal = AppDimens.spacingMedium),
                    contentPadding = PaddingValues(vertical = AppDimens.spacingSmall),
                    verticalArrangement = Arrangement.Top
                ) {
                    item {
                        // 基本信息
                        Card(
                            modifier = Modifier.fillMaxWidth(),
                            elevation = CardDefaults.cardElevation(AppDimens.elevationSmall),
                            colors = CardDefaults.cardColors(
                                containerColor = MaterialTheme.colorScheme.surface
                            ),
                            shape = RoundedCornerShape(AppDimens.cornerRadiusMedium)
                        ) {
                            Column(
                                modifier = Modifier.padding(AppDimens.spacingMedium)
                            ) {
                                Text(
                                    "📄 编号：${record?.id}",
                                    style = MaterialTheme.typography.titleMedium
                                )
                                Text(
                                    "👨‍⚕️ 医生：${record?.doctor}",
                                    style = MaterialTheme.typography.bodyLarge
                                )
                                Text(
                                    "🧑 患者：${record?.patient_name}",
                                    style = MaterialTheme.typography.bodyLarge
                                )
                                Text(
                                    "📅 日期：${record?.date}",
                                    style = MaterialTheme.typography.bodySmall,
                                    color = MaterialTheme.colorScheme.onSurfaceVariant
                                )
                            }
                        }

                        Spacer(modifier = Modifier.height(AppDimens.spacingMedium))

                        // 显示眼底图像
                        Text(
                            "眼底图像",
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier.padding(bottom = AppDimens.spacingSmall)
                        )
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceAround
                        ) {
                            if (!record?.left_eye_url.isNullOrEmpty()) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    modifier = Modifier.weight(1f)
                                ) {
                                    Text("左眼图像")

                                    // 修复左眼图像URL拼接问题
                                    val baseUrl = BuildConfig.BASE_URL.trimEnd('/')
                                    val leftEyePath = record?.left_eye_url?.trimStart('/') ?: ""
                                    val leftEyeUrl = "$baseUrl/$leftEyePath"
                                    Image(
                                        painter = rememberAsyncImagePainter(leftEyeUrl),
                                        contentDescription = "左眼图像",
                                        modifier = Modifier
                                            .size(150.dp)
                                            .padding(AppDimens.spacingSmall),
                                        contentScale = ContentScale.Crop
                                    )
                                }
                            }

                            if (!record?.right_eye_url.isNullOrEmpty()) {
                                Column(
                                    horizontalAlignment = Alignment.CenterHorizontally,
                                    modifier = Modifier.weight(1f)
                                ) {
                                    Text("右眼图像")
                                    // 修复右眼图像URL拼接问题
                                    val baseUrl = BuildConfig.BASE_URL.trimEnd('/')
                                    val rightEyePath =
                                        record?.right_eye_url?.trimStart('/') ?: ""
                                    val rightEyeUrl = "$baseUrl/$rightEyePath"
                                    Image(
                                        painter = rememberAsyncImagePainter(rightEyeUrl),
                                        contentDescription = "右眼图像",
                                        modifier = Modifier
                                            .size(150.dp)
                                            .padding(AppDimens.spacingSmall),
                                        contentScale = ContentScale.Crop
                                    )
                                }
                            }
                        }

                        Spacer(modifier = Modifier.height(AppDimens.spacingMedium))

                        // 显示诊断结果
                        Text(
                            "🔍 诊断结果",
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier.padding(bottom = AppDimens.spacingSmall)
                        )
                        // 修复诊断结果部分的 AnimatedVisibility (第201~202行)
                        record?.diagnoses?.forEachIndexed { index, diagnosis ->
                            AnimatedVisibility(
                                visible = showContent,
                                enter = fadeIn(
                                    animationSpec = tween(
                                        delayMillis = 100 * (index + 1),
                                        durationMillis = AppAnimations.durationMedium
                                    )
                                )
                            ) {
                                Card(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(vertical = AppDimens.spacingSmall),
                                    elevation = CardDefaults.cardElevation(AppDimens.elevationSmall),
                                    colors = CardDefaults.cardColors(
                                        containerColor = when (diagnosis.risk_level) {
                                            "高危" -> Color(0xFFE57373) // 红色系
                                            "中危" -> Color(0xFFFFD54F) // 黄色系
                                            "低危" -> Color(0xFF81C784) // 绿色系
                                            else -> Color(0xFFEEEEEE)   // 浅灰色
                                        }
                                    ),
                                    shape = RoundedCornerShape(AppDimens.cornerRadiusMedium)
                                ) {
                                    Column(
                                        modifier = Modifier.padding(AppDimens.spacingMedium)
                                    ) {
                                        Text("疾病：${diagnosis.name}")
                                        Text("风险等级：${diagnosis.risk_level}")
                                    }
                                }
                            }
                        }

                        Spacer(modifier = Modifier.height(AppDimens.spacingMedium))

                        // 显示建议
                        Text(
                            "💡 建议",
                            style = MaterialTheme.typography.titleMedium,
                            modifier = Modifier.padding(bottom = AppDimens.spacingSmall)
                        )

                        // DeepSeek建议部分
                        AnimatedVisibility(
                            visible = showContent,
                            enter = fadeIn(
                                animationSpec = tween(
                                    delayMillis = 300,
                                    durationMillis = AppAnimations.durationMedium
                                )
                            )
                        ) {
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = AppDimens.spacingSmall),
                                elevation = CardDefaults.cardElevation(AppDimens.elevationSmall),
                                colors = CardDefaults.cardColors(
                                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                                ),
                                shape = RoundedCornerShape(AppDimens.cornerRadiusMedium)
                            ) {
                                Column(
                                    modifier = Modifier
                                        .padding(AppDimens.spacingMedium)
                                        .fillMaxWidth()
                                ) {
                                    Text(
                                        "DeepSeek建议",
                                        style = MaterialTheme.typography.titleSmall
                                    )
                                    // 2. 让长文本自动换行（明确设置softWrap = true）
                                    Text(
                                        text = record?.advice_deepseek ?: "无DeepSeek建议",
                                        modifier = Modifier.fillMaxWidth(),
                                        style = MaterialTheme.typography.bodyMedium,
                                        softWrap = true
                                    )
                                }
                            }
                        }

                        // 华佗建议部分
                        AnimatedVisibility(
                            visible = showContent,
                            enter = fadeIn(
                                animationSpec = tween(
                                    delayMillis = 300,
                                    durationMillis = AppAnimations.durationMedium
                                )
                            )
                        ) {
                            Card(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(vertical = AppDimens.spacingSmall),
                                elevation = CardDefaults.cardElevation(AppDimens.elevationSmall),
                                colors = CardDefaults.cardColors(
                                    containerColor = MaterialTheme.colorScheme.surfaceVariant
                                ),
                                shape = RoundedCornerShape(AppDimens.cornerRadiusMedium)
                            ) {
                                Column(
                                    modifier = Modifier
                                        .padding(AppDimens.spacingMedium)
                                        .fillMaxWidth()
                                ) {
                                    Text(
                                        "华佗建议",
                                        style = MaterialTheme.typography.titleSmall
                                    )
                                    // 2. 让长文本自动换行（明确设置softWrap = true）
                                    Text(
                                        text = record?.advice_huatuo ?: "无华佗建议",
                                        modifier = Modifier.fillMaxWidth(),
                                        style = MaterialTheme.typography.bodyMedium,
                                        softWrap = true
                                    )
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}